// 全新的聊天工具类 - 简化版本
const chatUtil = {
  // WebSocket连接
  socket: null,
  
  // 连接状态
  isConnected: false,
  
  // 消息回调
  messageCallback: null,
  
  // 状态回调
  statusCallback: null,

  /**
   * 连接WebSocket - 简化版本
   */
  connect(userId, userType = 'user') {
    return new Promise((resolve, reject) => {
      try {
        // 如果已连接，先断开
        if (this.socket) {
          this.disconnect()
        }
        
        const wsUrl = `ws://localhost:8087/ws/chat/${userId}/${userType}`
        console.log('🔗 连接WebSocket:', wsUrl)
        
        // 设置连接超时
        const connectTimeout = setTimeout(() => {
          console.error('⏰ WebSocket连接超时 (10秒)')
          this.disconnect()
          reject(new Error('连接超时，请检查网络或服务状态'))
        }, 10000)
        
        this.socket = wx.connectSocket({
          url: wsUrl,
          success: () => {
            console.log('📡 WebSocket连接请求已发送')
          },
          fail: (error) => {
            clearTimeout(connectTimeout)
            console.error('❌ WebSocket连接失败:', error)
            reject(new Error(`连接失败: ${error.errMsg || '网络错误'}`))
          }
        })
        
        // 监听连接打开
        this.socket.onOpen = () => {
          console.log('✅ WebSocket连接已打开')
          // 立即设置连接状态，不等待服务器确认
          this.isConnected = true
          clearTimeout(connectTimeout)
          if (this.statusCallback) {
            this.statusCallback('connected')
          }
          resolve()
        }
        
        // 监听消息
        this.socket.onMessage = (res) => {
          console.log('📨 收到WebSocket消息:', res.data)
          try {
            const message = JSON.parse(res.data)
            console.log('📊 解析后的消息:', message)
            
            // 处理连接确认消息（可选）
            if (message.type === 'connection' && message.status === 'success') {
              console.log('🎉 收到连接确认消息')
            }
            
            // 处理其他消息
            if (this.messageCallback) {
              this.messageCallback(message)
            }
          } catch (error) {
            console.error('❌ 解析消息失败:', error)
            // 处理非JSON消息
            if (this.messageCallback) {
              this.messageCallback({ content: res.data })
            }
          }
        }
        
        // 监听连接关闭
        this.socket.onClose = (res) => {
          clearTimeout(connectTimeout)
          console.log('🔌 WebSocket连接已关闭:', res)
          this.isConnected = false
          if (this.statusCallback) {
            this.statusCallback('disconnected')
          }
        }
        
        // 监听错误
        this.socket.onError = (error) => {
          clearTimeout(connectTimeout)
          console.error('💥 WebSocket连接错误:', error)
          this.isConnected = false
          if (this.statusCallback) {
            this.statusCallback('error')
          }
          reject(new Error(`连接错误: ${error.errMsg || '未知错误'}`))
        }
        
      } catch (error) {
        console.error('❌ 创建WebSocket连接失败:', error)
        reject(new Error(`创建连接失败: ${error.message}`))
      }
    })
  },
  
  /**
   * 断开连接
   */
  disconnect() {
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }
    this.isConnected = false
  },
  
  /**
   * 发送消息
   */
  sendMessage(message) {
    return new Promise((resolve, reject) => {
      if (!this.isConnected || !this.socket) {
        reject(new Error('WebSocket未连接'))
        return
      }
      
      try {
        const messageStr = JSON.stringify(message)
        this.socket.send({
          data: messageStr,
          success: () => {
            console.log('📤 消息发送成功:', message)
            resolve()
          },
          fail: (error) => {
            console.error('❌ 消息发送失败:', error)
            reject(error)
          }
        })
      } catch (error) {
        console.error('❌ 发送消息异常:', error)
        reject(error)
      }
    })
  },
  
  /**
   * 设置消息回调
   */
  setMessageCallback(callback) {
    this.messageCallback = callback
  },
  
  /**
   * 设置状态回调
   */
  setStatusCallback(callback) {
    this.statusCallback = callback
  },
  
  /**
   * 开始客服会话
   */
  async startChat(userId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://localhost:8087/chat/start',
          method: 'POST',
          data: { userId },
          header: {
            'Content-Type': 'application/json'
          },
          success: (response) => {
            if (response.statusCode === 200) {
              resolve(response)
            } else {
              reject(new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`))
            }
          },
          fail: (error) => {
            reject(new Error(`网络请求失败: ${error.errMsg || '连接超时'}`))
          }
        })
      })
      
      if (res.data && res.data.success) {
        return res.data
      } else {
        throw new Error(res.data?.message || '开始会话失败')
      }
    } catch (error) {
      console.error('开始客服会话失败:', error)
      throw error
    }
  },
  
  /**
   * 获取会话消息
   */
  async getSessionMessages(sessionId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://localhost:8087/chat/messages',
          method: 'GET',
          data: { sessionId },
          success: (response) => {
            if (response.statusCode === 200) {
              resolve(response)
            } else {
              reject(new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`))
            }
          },
          fail: (error) => {
            reject(new Error(`网络请求失败: ${error.errMsg || '连接超时'}`))
          }
        })
      })
      
      if (res.data && res.data.success) {
        return res.data.messages || []
      } else {
        throw new Error(res.data?.message || '获取消息失败')
      }
    } catch (error) {
      console.error('获取会话消息失败:', error)
      throw error
    }
  },
  
  /**
   * 标记消息已读
   */
  async markMessageAsRead(messageId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://localhost:8087/chat/message/read',
          method: 'POST',
          data: { messageId },
          header: {
            'Content-Type': 'application/json'
          },
          success: (response) => {
            if (response.statusCode === 200) {
              resolve(response)
            } else {
              reject(new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`))
            }
          },
          fail: (error) => {
            reject(new Error(`网络请求失败: ${error.errMsg || '连接超时'}`))
          }
        })
      })
      
      return res.data && res.data.success
    } catch (error) {
      console.error('标记消息已读失败:', error)
      throw error
    }
  },
  
  /**
   * 关闭会话
   */
  async closeSession(sessionId) {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://localhost:8087/chat/session/close',
          method: 'POST',
          data: { sessionId },
          header: {
            'Content-Type': 'application/json'
          },
          success: (response) => {
            if (response.statusCode === 200) {
              resolve(response)
            } else {
              reject(new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`))
            }
          },
          fail: (error) => {
            reject(new Error(`网络请求失败: ${error.errMsg || '连接超时'}`))
          }
        })
      })
      
      return res.data && res.data.success
    } catch (error) {
      console.error('关闭会话失败:', error)
      throw error
    }
  }
}

module.exports = chatUtil

